<template>
  <!-- 添加和编辑发货计划 -->
  <a-modal :width="1200" v-model:visible="showEditPlanDialog" :title="currentData && currentData.id ? '编辑发货单' : '创建发货单'" title-align="start" :mask-closable="false" @cancel="closedDialog" :ok-loading="submitLoading" :on-before-ok="submitData">
    <div class="edit-w">
      <a-form ref="formRef" :model="formInfo" :rules="rules">
        <a-row v-if="currentData && currentData.id">
          <a-col :span="10">
            <a-form-item label="发货单号：" label-col-flex="130px">
              <p>{{ currentData.billNo }}</p>
            </a-form-item>
          </a-col>
          <a-col :span="7">
            <a-form-item label="创建人：" label-col-flex="130px">
              <p>{{ currentData.createUname }}</p>
            </a-form-item>
          </a-col>
          <a-col :span="7">
            <a-form-item label="创建时间：" label-col-flex="70px">
              <p>{{ $setTime(currentData.gmtCreate) }}</p>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="10">
            <a-form-item field="warehouse.warehouseCode" label="发货仓库：" label-col-flex="130px">
              <a-select v-model="formInfo.warehouse" placeholder="请选择" value-key="warehouseCode" allow-search @change="getFbaAndInventoryData">
                <a-option v-for="(warehouse, i) in useBaseData.warehouseList" :key="i" :value="warehouse" :label="warehouse.warehouseName" />
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="9" v-if="source == 'fba'">
            <a-form-item field="shop.shopId" label="店铺：" label-col-flex="70px">
              <a-select v-model="formInfo.shop" :disabled="currentData && currentData.id ? true : false" placeholder="请选择" value-key="id" allow-search @change="changeShop">
                <a-option v-for="(shop, i) in useBaseData.shopList" :key="i" :value="shop" :label="shop.shopName" />
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="5">
            <a-form-item field="logisticsMethod" label="物流方式：" label-col-flex="90px">
              <a-select v-model="formInfo.logisticsMethod" placeholder="请选择">
                <a-option value="海运" label="海运" />
                <a-option value="空运" label="空运" />
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="10">
            <a-form-item label="是否加急：" label-col-flex="130px">
              <a-radio-group v-model="formInfo.urgent">
                <a-radio :value="true">是</a-radio>
                <a-radio :value="false">否</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :span="14">
            <a-form-item label="附件：" label-col-flex="70px">
              <div class="flex">
                <ul style="margin-right: 10px" v-if="formInfo.attachment.length">
                  <li v-for="(url, i) in formInfo.attachment" style="margin-bottom: 4px" :key="i">
                    <a-tag color="arcoblue" closable>{{ url }}</a-tag>
                  </li>
                </ul>
                <a-upload action="/" :custom-request="uplaodFile" :show-file-list="false">
                  <template #upload-button>
                    <a-button size="mini" type="outline">
                      <template #icon>
                        <icon-upload />
                      </template>
                      <template #default>上传附件</template>
                    </a-button>
                  </template>
                </a-upload>
              </div>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="10">
            <a-form-item field="packageWarehouseCode" label="扣减包材库存:" label-col-flex="130px">
              <template #label>
                <span v-if="formInfo.needPackage" class="warningColor">*</span>
                <a-popover content="如果需要扣减包材库存，则包材选项必填">
                  <icon-question-circle />
                </a-popover>
                <span>扣减包材库存：</span>
              </template>
              <a-radio-group v-model="formInfo.needPackage">
                <a-radio :value="true">是</a-radio>
                <a-radio :value="false">否</a-radio>
              </a-radio-group>
              <a-select v-if="formInfo.needPackage" style="width: 214px" v-model="formInfo.packageWarehouse" placeholder="指定包材出货仓" value-key="warehouseCode" allow-search>
                <a-option v-for="(warehouse, i) in useBaseData.warehouseList" :key="i" :value="warehouse" :label="warehouse.warehouseName" />
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="14">
            <a-form-item field="remark" label="备注：" label-col-flex="70px">
              <a-textarea v-model="formInfo.remark" placeholder=" " allow-clear />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <div class="product-list-w">
        <div class="header flex-c">
          <p style="margin-right: 20px">已添加产品：{{ productList.length }}</p>
          <a-button v-if="source == 'fba'" style="margin-left: 20px" class="gray-outline" size="medium" @click="openChooseProductDialog">添加产品</a-button>
        </div>
        <div class="table-w" style="flex: 1">
          <a-table class="table-normal-line" ref="tableRef" :summary="true" :bordered="false" :data="productList" :scroll="{ x: '100%', y: '100%' }" size="mini" :pagination="false">
            <template #columns>
              <a-table-column data-index="sort" title="序号" :width="45" fixed="left">
                <template #cell="{ rowIndex }">
                  <p>{{ rowIndex + 1 }}</p>
                </template>
              </a-table-column>
              <a-table-column v-if="source != 'fba'" data-index="shop" title="店铺" :width="100" fixed="left">
                <template #cell="{ record }">
                  <TextLimit :rows="2">{{ record.shopName }}</TextLimit>
                </template>
              </a-table-column>
              <a-table-column data-index="salesmanName" title="销售员" :width="70" fixed="left" />
              <a-table-column v-if="source != 'fba'" data-index="shop" title="店铺" :width="100" fixed="left">
                <template #cell="{ record }">
                  <TextLimit :rows="2">{{ record.shopName }}</TextLimit>
                </template>
              </a-table-column>
              <a-table-column data-index="img" title="图片" :width="60" fixed="left">
                <template #cell="{ record }">
                  <ImgPopover :src="record.productImg">
                    <template #con>
                      <a-image width="40" height="40" fit="contain" :src="record.productImg" />
                    </template>
                  </ImgPopover>
                </template>
              </a-table-column>
              <a-table-column data-index="sku" title="SKU/类目" :width="100" fixed="left">
                <template #cell="{ record }">
                  <ShowSpuDetailBySku :val="record.sku" :showLimit="true" :rows="1" />
                  <p>{{ record.cateName || '--' }}</p>
                </template>
              </a-table-column>
              <a-table-column data-index="msku" title="MSKU/ASIN" :width="100" fixed="left">
                <template #cell="{ record }">
                  <TextLimit :rows="1">{{ record.msku || '--' }}</TextLimit>
                  <TextLimit :rows="1">{{ record.asin || '--' }}</TextLimit>
                </template>
              </a-table-column>
              <a-table-column data-index="fnsku" title="FNSKU" :width="100" fixed="left" />
              <a-table-column v-if="source != 'fba'" data-index="amtPurchaseRecommend" title="推荐发货量" :width="60" />
              <a-table-column data-index="planNum" :width="140">
                <template #title>
                  <p>
                    <span class="warningColor">*</span>
                    <span>发货数量</span>
                  </p>
                </template>
                <template #cell="{ record, rowIndex }">
                  <a-space>
                    <a-input-number v-model="record.planNum" style="width: 90px" :min="0" placeholder="" />
                    <a-button size="small" class="gray-outline" v-if="rowIndex < productList.length - 1" @click="setGlobal(record, 'planNum', rowIndex)">
                      <template #icon>
                        <icon-double-down />
                      </template>
                    </a-button>
                  </a-space>
                </template>
              </a-table-column>
              <a-table-column :width="180" key="packaging">
                <template #title>
                  <p>
                    <span v-if="formInfo.needPackage" class="warningColor">*</span>
                    <span>包材</span>
                  </p>
                </template>
                <template #cell="{ record, rowIndex }">
                  <a-space>
                    <a-select v-model="record.packaging" placeholder="选择包材" :trigger-props="{ autoFitPopupMinWidth: true }" style="width: 130px" value-key="id" allow-search>
                      <a-option v-for="(pack, i) in getPackingList(record.shopId)" :key="i" :value="pack" :label="pack.skuName" />
                    </a-select>
                    <a-button size="small" class="gray-outline" v-if="rowIndex < productList.length - 1" @click="setGlobal(record, 'packaging', rowIndex)">
                      <template #icon>
                        <icon-double-down />
                      </template>
                    </a-button>
                  </a-space>
                </template>
              </a-table-column>
              <a-table-column title="产品备注" :width="180">
                <template #cell="{ record, rowIndex }">
                  <div class="flex-c">
                    <a-space>
                      <a-input v-model="record.remark" style="width: 130px" placeholder="" allow-clear />
                      <a-button size="small" class="gray-outline" v-if="rowIndex < productList.length - 1" @click="setGlobal(record, 'remark', rowIndex)">
                        <template #icon>
                          <icon-double-down />
                        </template>
                      </a-button>
                    </a-space>
                  </div>
                </template>
              </a-table-column>
              <a-table-column data-index="amtInventory" title="发货仓可用库存" :width="70" />
              <a-table-column data-index="amtFba" title="FBA可用库存" :width="70" />
              <a-table-column data-index="amtFbaOnWay" title="FBA在途库存" :width="70" />
              <a-table-column data-index="amtPlan" title="计划采购数" :width="70" />
              <a-table-column data-index="amtPurchase" title="采购中数量" :width="70" />
              <a-table-column title="操作" :width="60" fixed="right">
                <template #cell="{ rowIndex }">
                  <a-button size="mini" type="text" v-if="productList.length > 1" @click="productList.splice(rowIndex, 1)">移除</a-button>
                </template>
              </a-table-column>
            </template>
            <template #summary-cell="{ column, record }">
              <p v-if="column.dataIndex == 'fnsku'">合计</p>
              <p v-else-if="['planNum', 'amtInventory', 'amtFba', 'amtFbaOnWay', 'amtPlan', 'amtPurchase'].includes(column.dataIndex)">{{ record[column.dataIndex] }}</p>
            </template>
          </a-table>
        </div>
      </div>
    </div>
  </a-modal>
  <!-- 选择智能补货产品产品 -->
  <ChooseDeliveryProduct v-if="showChooseProductDialog" :isShow="showChooseProductDialog" title="添加发货产品" :shopId="formInfo.shop.sellerMarketId" @closed="showChooseProductDialog = false" @success="chooseProduct" />
</template>
<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { updateFbaShipmentBySale, createFbaShipmentBySale, findFbaAndInventoryData } from '@/api/purchase'
  import { findPackingPageByFba } from '@/api/product'
  import useBaseDataStore from '@/store/modules/base-data'
  import { upload } from '@/api/base'
  import ChooseDeliveryProduct from './chooseDeliveryProduct.vue'

  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    currentData: {
      type: Object,
      default: () => {},
    },
    source: {
      type: String,
      default: 'fba',
    },
    defaultList: {
      type: Array,
      default: () => [],
    },
  })
  onMounted(() => {
    if (!props.currentData?.id) {
      useBaseData.getWareHouseList()
    }
    if (props.source == 'fba') {
      if (!props.currentData?.id) {
        useBaseData.getShopList()
      } else {
        setEditInfo()
      }
    }
    // 智能补货获取选中的商品
    if (props.source == 'replenishment') {
      getProductList()
    }
    getFbaAndInventoryData()
    getPackingPage()
  })

  const useBaseData = useBaseDataStore()
  const showEditPlanDialog = ref(props.isShow)
  const submitLoading = ref(false)
  const showChooseProductDialog = ref(false)
  const packingList = ref<Array<any>>([])
  const productList = ref<Array<any>>([])
  const formRef = ref()
  const formInfo = ref<any>({
    attachment: [],
    urgent: false,
    needPackage: true,
  })
  const rules = ref({
    'warehouse.warehouseCode': [{ required: true, message: '请选择仓库' }],
    'shop.shopId': [{ required: true, message: '请选择店铺' }],
    logisticsMethod: [{ required: true, message: '请选择物流方式' }],
  })

  function getProductList() {
    productList.value = props.defaultList.map((el: any) => {
      let obj = JSON.parse(JSON.stringify(el))
      return setItem(obj)
    })
  }
  // 获取全部包装列表
  async function getPackingPage() {
    let _params: any = {
      pageSize: 1000,
      pageNum: 1,
    }
    if (props.source == 'fba' && formInfo.value.shop?.sellerMarketId) {
      _params.sellerMarketIdList = [formInfo.value.shop.sellerMarketId]
    }
    packingList.value = []
    let res = await findPackingPageByFba(_params)
    packingList.value = res?.data?.records || []
  }
  // 包装可用列表
  function getPackingList(shopId: string) {
    if (props.source == 'fba') return packingList.value
    return packingList.value.filter((el: any) => {
      if (!el.shopList?.length) return true
      return el.shopList.find((item: any) => item.sellerMarketId == shopId)
    })
  }
  // 显示相关库存信息
  async function getFbaAndInventoryData() {
    if (!productList.value.length) return
    if (!formInfo.value.warehouse?.warehouseCode) return
    let items = productList.value.map((el: any) => {
      let shopId = props.currentData?.shopId || el.shopId
      return {
        warehouseCode: formInfo.value.warehouse.warehouseCode,
        msku: el.msku,
        shopId: shopId,
        sku: el.sku,
        sellerId: el.sellerId,
      }
    })
    const res: any = await findFbaAndInventoryData({ items })
    let inventoryList = res?.data || []

    productList.value.forEach((el: any, i: number) => {
      let keys = ['amtInventory', 'amtFba', 'amtFbaOnWay', 'amtPlan', 'amtPurchase']
      keys.forEach((key: string) => {
        el[key] = inventoryList[i]?.[key]
      })
    })
  }
  // 编辑信息回显
  function setEditInfo() {
    formInfo.value.needPackage = props.currentData.needPackage
    formInfo.value.remark = props.currentData.remark
    formInfo.value.logisticsMethod = props.currentData.logisticsMethod
    formInfo.value.attachment = props.currentData.attachment ? props.currentData.attachment.split(',') : []
    formInfo.value.shop = useBaseData.shopList?.find((shop: any) => shop.sellerId == props.currentData.sellerId && shop.marketplaceId == props.currentData.marketplaceId)
    if (props.currentData.packageWarehouseCode) {
      formInfo.value.packageWarehouse = {
        warehouseCode: props.currentData.packageWarehouseCode,
        warehouseName: props.currentData.packageWarehouseName,
      }
    }
    if (props.currentData.warehouseCode) {
      formInfo.value.warehouse = {
        warehouseCode: props.currentData.warehouseCode,
        warehouseName: props.currentData.warehouseCode,
      }
    }
    // 包装回显
    productList.value = []
    props.currentData.skuDetails?.forEach((el: any) => {
      let obj = JSON.parse(JSON.stringify(el))
      if (el.packageId) {
        obj.packaging = {
          id: el.packageId,
          skuName: el.packageName,
          sku: el.packageSku,
        }
      }
      productList.value.push(obj)
    })
  }

  // 校验数据
  async function validateData() {
    let valid = await formRef.value.validate((valid: any) => valid)
    // 需要扣减包材的时候校验包装库存
    if (formInfo.value.needPackage && !formInfo.value.packageWarehouse?.warehouseCode) {
      formRef.value.setFields({
        packageWarehouseCode: {
          status: 'error',
          message: '请选择包材指定出货仓',
        },
      })
      return false
    }
    if (valid) return false

    if (!productList.value.length) {
      Message.error('请最少选择一个产品')
      return false
    }
    let flag = false
    let packageFlag = false
    productList.value.forEach((el: any) => {
      if (!el.planNum) {
        flag = true
      }
      if (formInfo.value.needPackage && !el.packaging?.id) {
        packageFlag = true
      }
    })
    if (flag) {
      Message.error('发货数量必填且必须大于1')
      return false
    }
    if (packageFlag) {
      Message.error('包材必选')
      return false
    }
    return true
  }
  function setSavaItem() {
    let list = JSON.parse(JSON.stringify(productList.value))
    list.forEach((el: any) => {
      el.packageId = el.packaging?.id
      el.packageName = el.packaging?.skuName
      el.packageSku = el.packaging?.sku
      delete el.packaging
    })
    return list
  }
  // 选择产品
  async function submitData() {
    let valid = await validateData()
    if (!valid) return false
    let params: any = {
      marketplaceId: formInfo.value.shop?.marketplaceId,
      sellerId: formInfo.value.shop?.sellerId,
      needPackage: formInfo.value.needPackage,
      urgent: formInfo.value.urgent,
      warehouseCode: formInfo.value.warehouse?.warehouseCode,
      warehouseName: formInfo.value.warehouse?.warehouseName,
      attachment: formInfo.value.attachment?.join(','),
      remark: formInfo.value.remark,
      logisticsMethod: formInfo.value.logisticsMethod,
      skuDetails: setSavaItem(),
    }
    if (formInfo.value.needPackage) {
      params.packageWarehouseCode = formInfo.value.packageWarehouse?.warehouseCode
      params.packageWarehouseName = formInfo.value.packageWarehouse?.warehouseName
    }
    let res: any
    if (props.currentData?.id) {
      params.id = props.currentData.id
      res = await updateFbaShipmentBySale(params)
    } else {
      res = await createFbaShipmentBySale(params)
    }
    if (!res) return false
    Message.success('保存成功！')
    emit('success')
    emit('closed')
  }
  // 切换店铺
  function changeShop() {
    productList.value = []
    getFbaAndInventoryData()
    getPackingPage()
  }
  //设置全局
  async function setGlobal(item: any, key: string, rowIndex: number) {
    let val = item[key]
    productList.value.forEach((el: any, i: number) => {
      if (i > rowIndex) el[key] = val
    })
  }
  // 上传附件
  const uplaodFile: any = async (options: any) => {
    let { fileItem } = options
    let formData = new FormData()
    formData.append('file', fileItem.file)
    const res: any = await upload(formData)
    if (res?.data?.publicUrl) {
      formInfo.value.attachment.push(res.data.publicUrl)
    }
  }
  // 关闭
  function closedDialog() {
    showEditPlanDialog.value = false
    emit('closed')
  }
  // 初始化产品数据
  function setItem(item: any) {
    item.salesmanId = item.salesmans?.[0]?.salesmanId
    item.salesmanName = item.salesmans?.[0]?.salesmanName
    item.planAmt = item.amtPurchaseRecommend
    item.productImg = item?.productImgs?.[0]
    item.urgent = false
    delete item.salesmans
    delete item.productImgs
    return item
  }
  // 选中产品
  function chooseProduct(list: Array<any>) {
    list.forEach((el: any) => {
      productList.value.push(setItem(el))
    })
    getFbaAndInventoryData()
  }
  // 打开添加产品
  function openChooseProductDialog() {
    if (!formInfo.value.shop?.sellerMarketId) {
      Message.error('请先选择店铺')
      return
    }
    showChooseProductDialog.value = true
  }
</script>
<style lang="less" scoped>
  .edit-w {
    height: calc(84vh - 140px);
    display: flex;
    flex-direction: column;
    overflow-y: hidden;
  }
  .product-list-w {
    flex: 1;
    background-color: #fff;
    display: flex;
    padding: 0 20px;
    flex-direction: column;
    overflow: hidden;
  }
  .header {
    font-weight: bold;
    border-left: 2px solid rgb(var(--primary-6));
    padding-left: 20px;
    margin-bottom: 10px;
  }
  .table-w {
    flex: 1;
    overflow: hidden;
  }
</style>
